package com.itqf.web;

import com.itqf.entity.TbItem;
import com.itqf.service.TbITemService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/11/11
 * @Time: 下午5:21
 */
@WebServlet(value = "/find",initParams = {@WebInitParam(name = "encoding",value = "utf-8")})
/*initParams   web.xml
 <servlet>   servlet的初始化参数
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
*
 */
public class TbItemServlet  extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println(config.getInitParameter("encoding"));
    }


    //从Spring容器中获取TbItemService对象
    //ApplicationContext ac = new ClassPathXmlApplicationContext("");

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从Spring容器中获取TbItemService对象
        //1.web.xml 配置监听器，监听器中已经加载了Spring配置文件， ServletContextListener
        //2. WebApplicationContext    req.getServletContext()
        //<context-param>  servletContext  的上下文的初始化参数
        System.out.println(req.getServletContext().getInitParameter("contextConfigLocation"));

     WebApplicationContext webAc =  WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());

     TbITemService tbITemService = (TbITemService) webAc.getBean("tbItemService");

     List<TbItem> list = tbITemService.findAll();

     req.setAttribute("tbItemList",list);

     req.getRequestDispatcher("show.jsp").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
